package com.alogic.es.xscript;

import com.alogic.es.client.IndexerTool;
import com.alogic.es.core.Indexer;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * Indexer
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsIndexer extends NS {

    /**
     * indexer的id
     */
    protected String indexerId = "default";

    /**
     * 当前对象id
     */
    protected String cid = "$es-indexer";

    protected String $endpoint;

    public EsIndexer(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        indexerId = PropertiesConstants.getString(p,"indexerId",indexerId,true);
        cid = PropertiesConstants.getString(p,"cid",cid,true);
        $endpoint = PropertiesConstants.getRaw(p,"endpoint","");
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        Indexer indexer = IndexerTool.getIndexer(indexerId);
        if (indexer != null){
            ctx.setObject(cid, indexer);
            indexer.writeProperties(ctx);

            String endpoint = PropertiesConstants.transform(ctx,$endpoint,"");
            if (StringUtils.isNotEmpty(endpoint)){
                ctx.SetValue("$es.endpoint",endpoint);
            }
            try {
                super.onExecute(root, current, ctx, watcher);
            }finally{
                ctx.removeObject(cid);
            }
        }else{
            log(String.format("[%s] Indexer is not found,id = %s",this.getXmlTag(),indexerId),"warnning");
        }
    }
}
